import React, { FC, useEffect, useState, MouseEvent } from 'react'
import styles from './EditCanvas.module.scss'
import { ComponentInfoType, changeSelectedId } from '../../../store/componentReducer'
import useGetComponentinfo from '../../../hooks/useGetComponentinfo.ts'
import axios from 'axios'
import { getComponentConByType } from '../../../components/QuestionComponents/index.ts'
import { useDispatch } from 'react-redux'
import classNames from 'classnames'
import useBindCanvasKeyPress from '../../../hooks/useBindCanvasKeyPress.ts'

const EditCanvas: FC = () => {
  const dispatch = useDispatch()
  const { componentList, selectedId } = useGetComponentinfo()
  function getComponent(componentInfo: ComponentInfoType) {
    const { type, props } = componentInfo
    const componentConf = getComponentConByType(type)
    if (componentConf === null) return null
    const { Component } = componentConf
    return <Component {...props} />
  }
  function handleClick(event: MouseEvent, id: string) {
    event.stopPropagation() //阻止冒泡
    dispatch(changeSelectedId(id))
  }
  //绑定快捷件
  useBindCanvasKeyPress()

  return (
    <div className={styles.canvas}>
      {componentList.length > 0 &&
        componentList
          .filter(e => !e.isHidden)
          .map(c => {
            const { fe_id, isLock } = c
            const wrapperDefaultClassName = styles['component-warper']

            const selectedClassName = styles.selected
            const lockedClassName = styles.locked
            const wrapperClassName = classNames({
              [wrapperDefaultClassName]: true,
              [selectedClassName]: selectedId === fe_id,
              [lockedClassName]: isLock,
            })

            return (
              <div key={fe_id} onClick={e => handleClick(e, fe_id)} className={wrapperClassName}>
                <div className={styles.component}>{getComponent(c)}</div>
              </div>
            )
          })}
    </div>
  )
}

export default EditCanvas
